import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import { Layout, Spin, message, Tabs, Button, Table, Tooltip, Empty, Modal, Card, Space } from 'antd';
import { DownOutlined, RightOutlined, EditOutlined, ReloadOutlined, PlusOutlined, DeleteOutlined, ExpandOutlined, NodeExpandOutlined, NodeCollapseOutlined, ProjectOutlined, ZoomInOutlined, ZoomOutOutlined, FullscreenOutlined } from '@ant-design/icons';
import ReactFlow, { 
  Background, 
  Controls, 
  MiniMap, 
  useNodesState, 
  useEdgesState, 
  Panel, 
  MarkerType, 
  Handle, 
  Position 
} from 'reactflow';
import 'reactflow/dist/style.css';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import { FiSettings } from 'react-icons/fi';
import { format } from 'date-fns';

// 导入ProcessFlowChart组件
import ProcessFlowChart from './ProcessFlowChart';

// 导入自定义图标
import productProcessIcon from '../assets/icons/产品工艺图标.png';
import operationIcon from '../assets/icons/工序图标.png';
import stepIcon from '../assets/icons/工步图标.png';
import resourceGroupIcon from '../assets/资源组图标.png';
import resourceIcon from '../assets/资源图标.png';
import productGroupIcon from '../assets/产品组图标.png';
import productIcon from '../assets/产品图标.png';

// 添加自定义CSS样式
const customStyles = `
  .process-detail-container {
    overflow: hidden !important;
  }
  
  .process-detail-container .ant-layout-content {
    overflow: hidden !important;
  }
  
  .process-detail-container .right-content-area {
    overflow: hidden !important;
  }
  
  .process-detail-container .content-wrapper {
    overflow: hidden !important;
    height: 100%;
  }
  
  .process-detail-container .tree-container {
    overflow-y: auto;
    overflow-x: hidden;
  }
  
  /* 滚动条样式 */
  .process-detail-container .tree-container::-webkit-scrollbar {
    width: 8px !important;
    background-color: #f1f1f1 !important;
    display: block !important;
  }
  
  .process-detail-container .tree-container::-webkit-scrollbar-thumb {
    background-color: #c1c1c1 !important;
    border-radius: 4px !important;
  }
  
  .process-detail-container .tree-container::-webkit-scrollbar-thumb:hover {
    background-color: #a8a8a8 !important;
  }
  
  /* 树形结构控制按钮样式 */
  .tree-control-buttons {
    display: flex;
    justify-content: center;
    margin-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 8px;
  }
  
  .tree-control-buttons .ant-btn {
    padding: 0 8px;
    height: 28px;
    line-height: 28px;
    font-size: 13px;
    border-radius: 2px;
    margin: 0 4px;
  }
  
  .tree-control-buttons .ant-btn:hover {
    color: #1766a3;
    background-color: #f0f7ff;
  }
  
  .tree-control-buttons .anticon {
    font-size: 14px;
  }
  
  .detail-tabs {
    margin-bottom: 16px;
  }
  
  .detail-tabs .ant-tabs-nav {
    margin-bottom: 0;
  }
  
  .detail-tabs .ant-tabs-tab {
    padding: 12px 16px;
  }
  
  .detail-tabs .ant-tabs-tab-active {
    font-weight: bold;
  }
  
  .detail-tabs .ant-tabs-ink-bar {
    background-color: #1766a3;
    height: 3px;
  }
  
  .detail-content {
    padding: 16px;
    background: #fff;
    border-top: 1px solid #e8e8e8;
  }
  
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .detail-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
  
  .detail-item {
    display: grid;
    grid-template-columns: 120px 1fr;
    margin-bottom: 16px;
    align-items: center;
  }
  
  .detail-label {
    color: #666;
    text-align: right;
    padding-right: 16px;
    font-weight: 500;
  }
  
  .detail-value {
    color: #333;
  }
  
  .sub-detail-content {
    margin-top: 20px;
    border-top: 1px dashed #e8e8e8;
    padding-top: 16px;
  }
  
  .sub-detail-content .detail-header {
    margin-bottom: 12px;
  }
  
  .sub-detail-content .detail-title {
    font-size: 15px;
    color: #1766a3;
  }
  
  .custom-tabs {
    display: flex;
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 16px;
  }
  
  .custom-tab {
    padding: 12px 16px;
    cursor: pointer;
    position: relative;
    font-size: 14px;
  }
  
  .custom-tab.active {
    color: #1766a3;
    font-weight: bold;
  }
  
  .custom-tab.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2px;
    background-color: #1766a3;
  }
  
  .parameter-table {
    margin-top: 16px;
  }
  
  .parameter-table .ant-table-thead > tr > th {
    background-color: #f7f7f7;
    font-weight: bold;
    color: #333;
  }
  
  .parameter-table .ant-table-tbody > tr > td {
    padding: 8px 16px;
  }
  
  .parameter-table .ant-table-tbody > tr:hover > td {
    background-color: #f0f7ff;
  }
  
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .table-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
  
  /* 移动端适配样式 */
  @media screen and (max-width: 576px) {
    .process-detail-container .tree-container {
      max-height: 300px;
      border-bottom: 1px solid #e8e8e8;
    }
    
    .process-detail-container .custom-tree {
      padding-bottom: 16px;
    }
    
    .process-detail-container .right-content-area {
      border-top: 1px solid #e8e8e8;
    }
    
    .process-detail-container .custom-tabs {
      overflow-x: auto;
      flex-wrap: nowrap;
      justify-content: flex-start;
      white-space: nowrap;
      padding-bottom: 4px;
    }
    
    .process-detail-container .custom-tabs::-webkit-scrollbar {
      height: 4px;
      background-color: #f1f1f1;
    }
    
    .process-detail-container .custom-tabs::-webkit-scrollbar-thumb {
      background-color: #c1c1c1;
      border-radius: 4px;
    }
    
    .process-detail-container .custom-tab {
      padding: 8px 10px;
      font-size: 12px;
      min-width: 70px;
      text-align: center;
    }
    
    .tree-control-buttons {
      justify-content: space-around;
      padding: 6px 0;
    }
    
    .tree-control-buttons .ant-btn {
      padding: 0 4px;
      margin: 0 2px;
      min-width: 28px;
      height: 28px;
    }
    
    .detail-item {
      grid-template-columns: 90px 1fr;
    }
    
    .detail-tabs .ant-tabs-tab {
      padding: 8px 12px;
    }
    
    .custom-tab {
      padding: 8px 12px;
      font-size: 13px;
    }
    
    .detail-content {
      padding: 12px;
    }
    
    .parameter-table .ant-table-tbody > tr > td {
      padding: 4px 8px;
      font-size: 12px;
    }
    
    /* 树节点在移动端的样式调整 */
    .process-detail-container .tree-container .custom-tree div[data-key] > div {
      padding: 6px 0 !important;
    }
    
    .process-detail-container .tree-container .custom-tree span {
      font-size: 13px;
    }
    
    .process-detail-container .tree-container .custom-tree img {
      width: 14px !important;
      height: 14px !important;
    }
  }
`;

const { Content } = Layout;

const ProcessDetail = ({ routeId, code }) => {
  const [loading, setLoading] = useState(false);
  const [processData, setProcessData] = useState(null);
  const [processDetail, setProcessDetail] = useState(null);
  const [templateInfo, setTemplateInfo] = useState(null);
  const [treeData, setTreeData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [isMobile, setIsMobile] = useState(false);
  const [activeTab, setActiveTab] = useState('details');
  const [stepInfoMap, setStepInfoMap] = useState({});
  const [selectedNode, setSelectedNode] = useState(null);
  const [operationDetail, setOperationDetail] = useState(null);
  const [operationLoading, setOperationLoading] = useState(false);
  const [stepDetail, setStepDetail] = useState(null);
  const [stepLoading, setStepLoading] = useState(false);
  // 新增参数、资源、材料详情相关状态
  const [parameterDetail, setParameterDetail] = useState(null);
  const [parameterLoading, setParameterLoading] = useState(false);
  const [resourceDetail, setResourceDetail] = useState(null);
  const [resourceLoading, setResourceLoading] = useState(false);
  const [materialDetail, setMaterialDetail] = useState(null);
  const [materialLoading, setMaterialLoading] = useState(false);
  const [detailType, setDetailType] = useState(null); // 'parameter', 'resource', 'material'
  
  const [expandMode, setExpandMode] = useState('all'); // 'operations', 'steps', 'all'
  const treeContainerRef = useRef(null);
  const tableRef = useRef(null);
  // 新增流程图相关状态
  const [flowChartVisible, setFlowChartVisible] = useState(false);
  const [flowChartLoading, setFlowChartLoading] = useState(false);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取工艺详情
  useEffect(() => {
    const fetchProcessDetail = async () => {
      if (!routeId) return;
      
      setLoading(true);
      try {
        // 获取工艺流程结构
        const response = await axios.get(`${API_BASE_URL}/api/product_process_route/${routeId}/detail`);
        
        if (response.data && response.data.code === 200) {
          setProcessData(response.data.data);
          // 构建树形数据结构
          const treeNodes = buildTreeData(response.data.data);
          setTreeData(treeNodes);
          
          // 展开所有节点
          const allKeys = getAllKeys(treeNodes);
          setExpandedKeys(allKeys);
          // 设置初始展开模式为全部
          setExpandMode('all');
          
          // 获取工艺基本信息
          fetchProcessInfo(routeId);
        } else {
          message.error('获取工艺详情失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('获取工艺详情错误:', error);
        message.error('获取工艺详情失败: ' + (error.message || '网络错误'));
      } finally {
        setLoading(false);
      }
    };
    
    fetchProcessDetail();
  }, [routeId]);
  
  // 监听选项卡变化，加载相应数据
  useEffect(() => {
    // 选项卡变化时的处理逻辑
  }, [activeTab, routeId]);
  
  // 获取工艺基本信息
  const fetchProcessInfo = async (id) => {
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_process_route/${id}`);
      
      if (response.data && response.data.code === 200) {
        setProcessDetail(response.data.data);
        
        // 如果有模板ID，获取模板信息
        if (response.data.data && response.data.data.template_id) {
          fetchTemplateInfo(response.data.data.template_id);
        }
      } else {
        message.error('获取工艺基本信息失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取工艺基本信息错误:', error);
      message.error('获取工艺基本信息失败: ' + (error.message || '网络错误'));
    }
  };
  
  // 获取模板信息
  const fetchTemplateInfo = async (templateId) => {
    try {
      const response = await axios.get(`${API_BASE_URL}/api/process_template_info/${templateId}`);
      
      if (response.data && response.data.code === 200) {
        setTemplateInfo(response.data.data);
      } else {
        message.error('获取模板信息失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取模板信息错误:', error);
      message.error('获取模板信息失败: ' + (error.message || '网络错误'));
    }
  };
  
  // 获取工步详情信息
  const fetchStepInfos = async (stepIds) => {
    try {
      // 创建一个临时的工步信息映射
      const tempStepInfoMap = { ...stepInfoMap };
      
      // 并行获取每个工步的详细信息
      const promises = stepIds.map(async (id) => {
        if (tempStepInfoMap[id]) return; // 如果已经有了，就不再获取
        
        try {
          const response = await axios.get(`${API_BASE_URL}/api/product_process_step/${id}`);
          if (response.data && response.data.code === 200) {
            tempStepInfoMap[id] = response.data.data;
          }
        } catch (error) {
          console.error(`获取工步 ${id} 详情失败:`, error);
        }
      });
      
      // 等待所有请求完成
      await Promise.all(promises);
      
      // 更新工步信息映射
      setStepInfoMap(tempStepInfoMap);
    } catch (error) {
      console.error('获取工步信息错误:', error);
    }
  };


  



  


  // 构建树形数据结构
  const buildTreeData = (data) => {
    const treeNodes = [
      {
        key: `route-${data.id}`,
        title: data.name,
        code: data.code,
        iconSrc: productProcessIcon,
        type: 'route',
        children: []
      }
    ];
    
    // 添加工序节点
    if (data.operations && data.operations.length > 0) {
      data.operations.forEach((operation, opIndex) => {
        const operationCode = operation.code || `${opIndex + 1}`;
        const operationNode = {
          key: `operation-${operation.id}`,
          title: operation.name,
          displayTitle: `${operationCode} ${operation.name}`,
          code: operation.code,
          sequence: operation.sequence,
          estimatedTime: operation.estimated_time,
          iconSrc: operationIcon,
          type: 'operation',
          children: []
        };
        
        // 添加工步节点
        if (operation.steps && operation.steps.length > 0) {
          operation.steps.forEach((step, stepIndex) => {
            const stepCode = step.code || `${operationCode}-${stepIndex + 1}`;
            const stepNode = {
              key: `step-${step.id}`,
              title: step.name,
              displayTitle: `${stepCode} ${step.name}`,
              code: step.code,
              sequence: step.sequence,
              estimatedTime: step.estimated_time,
              iconSrc: stepIcon,
              type: 'step',
              children: []
            };
            
            // 添加工艺参数节点
            if (step.parameters && step.parameters.length > 0) {
              const parametersNode = {
                key: `parameters-${step.id}`,
                title: '工艺参数',
                icon: <FiSettings />,
                type: 'parameters',
                children: step.parameters.map(param => ({
                  key: `parameter-${param.id}`,
                  title: param.param_name || param.name || `参数${param.id}`,
                  value: param.value,
                  unit: param.unit,
                  type: 'parameter',
                }))
              };
              stepNode.children.push(parametersNode);
            }
            
            // 添加资源节点
            if (step.resources && step.resources.length > 0) {
              const resourcesNode = {
                key: `resources-${step.id}`,
                title: '资源',
                iconSrc: resourceGroupIcon,
                type: 'resources',
                children: step.resources.map(resource => ({
                  key: `resource-${resource.id}`,
                  title: resource.resource_name || `资源${resource.id}`,
                  quantity: resource.quantity,
                  // 根据resource类型选择图标
                  iconSrc: resource.source_type === 'self_made' ? resourceGroupIcon : resourceIcon,
                  type: 'resource',
                }))
              };
              stepNode.children.push(resourcesNode);
            }
            
            // 添加材料节点
            if (step.materials && step.materials.length > 0) {
              const materialsNode = {
                key: `materials-${step.id}`,
                title: '材料',
                iconSrc: productGroupIcon,
                type: 'materials',
                children: step.materials.map(material => ({
                  key: `material-${material.id}`,
                  title: material.product_name || material.material_name || `材料${material.id}`,
                  quantity: material.quantity,
                  unit: material.unit,
                  // 根据material类型选择图标
                  iconSrc: 
                    material.material_type === '零部件' || 
                    material.material_type === '成品' ? 
                    productGroupIcon : productIcon,
                  type: 'material',
                }))
              };
              stepNode.children.push(materialsNode);
            }
            
            operationNode.children.push(stepNode);
          });
        }
        
        treeNodes[0].children.push(operationNode);
      });
    }
    
    return treeNodes;
  };

  // 递归获取所有节点的key，用于默认展开
  const getAllKeys = (data) => {
    let keys = [];
    data.forEach(item => {
      keys.push(item.key);
      if (item.children && item.children.length > 0) {
        keys = [...keys, ...getAllKeys(item.children)];
      }
    });
    return keys;
  };

  // 切换节点展开/折叠
  const toggleNode = (key) => {
    // 当手动切换节点时，重置展开模式为自定义
    setExpandMode('custom');
    if (expandedKeys.includes(key)) {
      setExpandedKeys(expandedKeys.filter(k => k !== key));
    } else {
      setExpandedKeys([...expandedKeys, key]);
    }
  };
  
  // 展开至工序级别
  const expandToOperations = () => {
    // 创建一个新的展开键数组
    let newExpandedKeys = [];
    
    // 添加工艺路线节点
    if (treeData.length > 0) {
      const routeNode = treeData[0];
      newExpandedKeys.push(routeNode.key);
      
      // 只添加工序节点的key
      if (routeNode.children && routeNode.children.length > 0) {
        routeNode.children.forEach(operationNode => {
          if (operationNode.type === 'operation') {
            newExpandedKeys.push(operationNode.key);
          }
        });
      }
    }
    
    // 设置展开模式为工序级别
    setExpandMode('operations');
    // 直接设置新的展开键数组，覆盖原有的展开状态
    setExpandedKeys(newExpandedKeys);
  };
  
  // 展开至工步级别
  const expandToSteps = () => {
    // 创建一个新的展开键数组
    let newExpandedKeys = [];
    
    // 添加工艺路线节点
    if (treeData.length > 0) {
      const routeNode = treeData[0];
      newExpandedKeys.push(routeNode.key);
      
      // 添加工序和工步节点的key
      if (routeNode.children && routeNode.children.length > 0) {
        routeNode.children.forEach(operationNode => {
          if (operationNode.type === 'operation') {
            newExpandedKeys.push(operationNode.key);
            
            // 添加工步节点
            if (operationNode.children && operationNode.children.length > 0) {
              operationNode.children.forEach(stepNode => {
                if (stepNode.type === 'step') {
                  newExpandedKeys.push(stepNode.key);
                  // 不添加工步下的子节点（参数、资源、材料）
                }
              });
            }
          }
        });
      }
    }
    
    // 设置展开模式为工步级别
    setExpandMode('steps');
    // 直接设置新的展开键数组，覆盖原有的展开状态
    setExpandedKeys(newExpandedKeys);
  };
  
  // 全部展开
  const expandAll = () => {
    // 使用getAllKeys获取所有节点的key
    const allKeys = getAllKeys(treeData);
    // 设置展开模式为全部
    setExpandMode('all');
    // 直接设置新的展开键数组，覆盖原有的展开状态
    setExpandedKeys(allKeys);
  };

  // 处理参数节点点击
  const handleParameterClick = (e, node) => {
    try {
      e.stopPropagation(); // 防止触发父节点的展开/折叠
      
      // 设置选中的节点
      setSelectedNode(node.key);
      
      // 获取参数ID并加载参数详情
      const parameterId = node.key.replace('parameter-', '');
      if (!parameterId || isNaN(parseInt(parameterId, 10))) {
        message.error('无效的参数ID');
        return;
      }
      
      // 清除之前的详情
      setDetailType('parameter');
      setParameterDetail(null);
      
      // 获取参数详情
      fetchParameterDetail(parameterId);
      
      // 切换到参数详情选项卡
      setActiveTab('parameter');
    } catch (error) {
      console.error('处理参数点击事件错误:', error);
      message.error('处理参数点击失败: ' + (error.message || '未知错误'));
      // 确保状态正确设置，即使出错也能显示空状态
      setParameterDetail(null);
      setDetailType('parameter');
      setActiveTab('parameter');
    }
  };



  // 处理资源节点点击
  const handleResourceClick = (e, node) => {
    e.stopPropagation(); // 防止触发父节点的展开/折叠
    
    // 设置选中的节点
    setSelectedNode(node.key);
    
    // 获取资源ID并加载资源详情
    const resourceId = node.key.replace('resource-', '');
    fetchResourceDetail(resourceId);
    
    // 切换到资源详情选项卡
    setActiveTab('resource');
  };



  // 处理材料节点点击
  const handleMaterialClick = (e, node) => {
    e.stopPropagation(); // 防止触发父节点的展开/折叠
    
    // 设置选中的节点
    setSelectedNode(node.key);
    
    // 获取材料ID并加载材料详情
    const materialId = node.key.replace('material-', '');
    fetchMaterialDetail(materialId);
    
    // 切换到材料详情选项卡
    setActiveTab('material');
  };



  // 处理工序节点点击
  const handleOperationClick = (e, node) => {
    // 设置选中的节点
    setSelectedNode(node.key);
    
    // 清除之前的参数、资源或材料详情
    setParameterDetail(null);
    setResourceDetail(null);
    setMaterialDetail(null);
    setDetailType(null);
    
    // 获取工序ID并加载工序详情
    const operationId = node.key.replace('operation-', '');
    fetchOperationDetail(operationId);
    
    // 切换到工序详情选项卡
    setActiveTab('operation');
  };
  
  // 获取工序详情
  const fetchOperationDetail = async (operationId) => {
    if (!operationId) return;
    
    setOperationLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_process_operation/${operationId}`);
      
      if (response.data && response.data.code === 200) {
        setOperationDetail(response.data.data);
      } else {
        message.error('获取工序详情失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取工序详情错误:', error);
      message.error('获取工序详情失败: ' + (error.message || '网络错误'));
    } finally {
      setOperationLoading(false);
    }
  };

  // 处理工步节点点击
  const handleStepClick = (e, node) => {
    e.stopPropagation(); // 防止触发父节点的展开/折叠
    
    // 设置选中的节点
    setSelectedNode(node.key);
    
    // 清除之前的参数、资源或材料详情
    setParameterDetail(null);
    setResourceDetail(null);
    setMaterialDetail(null);
    setDetailType(null);
    
    // 获取工步ID并加载工步详情
    const stepId = node.key.replace('step-', '');
    fetchStepDetail(stepId);
    
    // 切换到工步详情选项卡
    setActiveTab('step');
  };
  
  // 获取工步详情
  const fetchStepDetail = async (stepId) => {
    if (!stepId) return;
    
    setStepLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_process_step/${stepId}`);
      
      if (response.data && response.data.code === 200) {
        setStepDetail(response.data.data);
      } else {
        message.error('获取工步详情失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取工步详情错误:', error);
      message.error('获取工步详情失败: ' + (error.message || '网络错误'));
    } finally {
      setStepLoading(false);
    }
  };

  // 获取参数详情
  const fetchParameterDetail = async (parameterId) => {
    if (!parameterId) {
      message.error('参数ID不能为空');
      setParameterLoading(false);
      return;
    }
    
    setParameterLoading(true);
    setDetailType('parameter');
    
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_process_parameter/${parameterId}`);
      
      if (response?.data?.code === 200) {
        // 检查返回的数据是否有效
        if (!response.data.data) {
          message.warning('返回的参数数据为空');
          setParameterDetail(null);
          return;
        }
        
        // 设置参数详情，使用可选链和默认值确保安全访问
        const parameterData = response.data.data;
        setParameterDetail({
          id: parameterData?.id,
          param_name: parameterData?.param_name || parameterData?.name || '未命名参数',
          param_value: parameterData?.param_value || parameterData?.value || '-',
          param_unit: parameterData?.param_unit || parameterData?.unit || '-',
          param_upper_limit: parameterData?.param_upper_limit || parameterData?.upper_limit || '-',
          param_lower_limit: parameterData?.param_lower_limit || parameterData?.lower_limit || '-',
          create_time: parameterData?.create_time || '-',
          update_time: parameterData?.update_time || '-',
          // 保留原始数据以备需要
          ...parameterData
        });
      } else {
        console.error('API返回错误:', response?.data?.message || '未知错误');
        message.error('获取参数详情失败: ' + (response?.data?.message || '未知错误'));
        // 清除已有的参数详情，防止显示旧数据
        setParameterDetail(null);
      }
    } catch (error) {
      console.error('获取参数详情错误:', error);
      message.error('获取参数详情失败: ' + (error.message || '网络错误'));
      // 清除已有的参数详情，防止显示旧数据
      setParameterDetail(null);
    } finally {
      setParameterLoading(false);
    }
  };
  
  // 获取资源详情
  const fetchResourceDetail = async (resourceId) => {
    if (!resourceId) return;
    
    setResourceLoading(true);
    setDetailType('resource');
    try {
      // 获取工艺资源基本信息
      const response = await axios.get(`${API_BASE_URL}/api/product_process_resource/${resourceId}`);
      
      if (response.data && response.data.code === 200) {
        const resourceData = response.data.data;
        
        // 如果有资源ID，获取资源库中的详细信息
        if (resourceData && resourceData.resource_id) {
          try {
            // 获取资源详情信息
            const resourceInfoResponse = await axios.get(`${API_BASE_URL}/api/resource_info/${resourceData.resource_id}`);
            
            if (resourceInfoResponse.data && resourceInfoResponse.data.code === 200) {
              const resourceInfo = resourceInfoResponse.data.data;
              
              // 尝试获取资源分类信息
              let categoryName = '-';
              if (resourceInfo.category_id) {
                try {
                  const categoryResponse = await axios.get(`${API_BASE_URL}/api/resource_category/${resourceInfo.category_id}`);
                  if (categoryResponse.data && categoryResponse.data.code === 200) {
                    categoryName = categoryResponse.data.data.name || '-';
                  }
                } catch (categoryError) {
                  console.warn('获取资源分类信息失败:', categoryError);
                }
              }
              
              // 尝试获取资源参数信息
              let parameters = [];
              try {
                const paramsResponse = await axios.get(`${API_BASE_URL}/api/resource_parameter`, {
                  params: {
                    resource_id: resourceData.resource_id,
                    page: 1,
                    size: 50
                  }
                });
                
                if (paramsResponse.data && paramsResponse.data.code === 200) {
                  parameters = paramsResponse.data.data.items || [];
                }
              } catch (paramsError) {
                console.warn('获取资源参数信息失败:', paramsError);
              }
              
              // 合并两个接口的数据，确保字段名称统一
              setResourceDetail({
                ...resourceData,
                ...resourceInfo,
                resource_name: resourceInfo.name || resourceData.resource_name || '-',
                resource_code: resourceInfo.code || resourceData.resource_code || '-',
                resource_type: resourceInfo.resource_type || '-',
                resource_model: resourceInfo.model || '-',
                resource_status: resourceInfo.status || '-',
                resource_source: resourceInfo.source_type || '-',
                resource_category: categoryName,
                resource_parameters: parameters,
                category_name: categoryName
              });
            } else {
              // 如果获取详情失败，仍然使用基本信息
              setResourceDetail({
                ...resourceData,
                resource_name: resourceData.resource_name || '-',
                resource_code: resourceData.resource_code || '-'
              });
              console.warn('获取资源库详情失败，使用基本信息');
            }
          } catch (detailError) {
            console.error('获取资源库详情错误:', detailError);
            // 如果获取详情出错，仍然使用基本信息
            setResourceDetail({
              ...resourceData,
              resource_name: resourceData.resource_name || '-',
              resource_code: resourceData.resource_code || '-'
            });
          }
        } else {
          // 如果没有关联资源ID，直接使用基本信息
          setResourceDetail({
            ...resourceData,
            resource_name: resourceData.resource_name || '-',
            resource_code: resourceData.resource_code || '-'
          });
        }
      } else {
        message.error('获取资源详情失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取资源详情错误:', error);
      message.error('获取资源详情失败: ' + (error.message || '网络错误'));
    } finally {
      setResourceLoading(false);
    }
  };
  
  // 获取材料详情
  const fetchMaterialDetail = async (materialId) => {
    if (!materialId) return;
    
    setMaterialLoading(true);
    setDetailType('material');
    try {
      // 获取工艺材料基本信息
      const response = await axios.get(`${API_BASE_URL}/api/product_process_material/${materialId}`);
      
      if (response.data && response.data.code === 200) {
        const materialData = response.data.data;
        
        // 如果有产品ID，获取产品库中的详细信息
        if (materialData && materialData.product_id) {
          try {
            const productInfoResponse = await axios.get(`${API_BASE_URL}/api/product_info/${materialData.product_id}`);
            
            if (productInfoResponse.data && productInfoResponse.data.code === 200) {
              // 合并两个接口的数据
              setMaterialDetail({
                ...materialData,
                ...productInfoResponse.data.data,
                material_name: productInfoResponse.data.data.name, // 确保有材料名称
                material_code: productInfoResponse.data.data.code, // 确保有材料编码
                material_type: productInfoResponse.data.data.product_type, // 产品类型作为材料类型
                material_spec: productInfoResponse.data.data.model, // 产品型号作为材料规格
                material_description: productInfoResponse.data.data.description // 产品描述作为材料描述
              });
            } else {
              // 如果获取详情失败，仍然使用基本信息
              setMaterialDetail(materialData);
              console.warn('获取产品库详情失败，使用基本信息');
            }
          } catch (detailError) {
            console.error('获取产品库详情错误:', detailError);
            // 如果获取详情出错，仍然使用基本信息
            setMaterialDetail(materialData);
          }
        } else {
          // 如果没有关联产品ID，直接使用基本信息
          setMaterialDetail(materialData);
        }
      } else {
        message.error('获取材料详情失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取材料详情错误:', error);
      message.error('获取材料详情失败: ' + (error.message || '网络错误'));
    } finally {
      setMaterialLoading(false);
    }
  };

  // 自定义渲染树节点
  const renderTreeNodes = (nodes, level = 0) => {
    return nodes.map(node => {
      const isExpanded = expandedKeys.includes(node.key);
      const hasChildren = node.children && node.children.length > 0;
      const isSelected = node.key === selectedNode;
      
      // 根据展开模式和节点类型判断是否应该显示此节点
      const shouldRenderNode = () => {
        // 如果是根节点或工序节点，总是显示
        if (node.type === 'route' || node.type === 'operation') {
          return true;
        }
        
        // 如果展开模式是"operations"，且节点类型是工步或其子节点，则不显示
        if (expandMode === 'operations' && (node.type === 'step' || node.type === 'parameters' || node.type === 'resources' || node.type === 'materials' || node.type === 'parameter' || node.type === 'resource' || node.type === 'material')) {
          return false;
        }
        
        // 如果展开模式是"steps"，且节点类型是工步的子节点，则不显示
        if (expandMode === 'steps' && (node.type === 'parameters' || node.type === 'resources' || node.type === 'materials' || node.type === 'parameter' || node.type === 'resource' || node.type === 'material')) {
          return false;
        }
        
        // 其他情况都显示
        return true;
      };
      
      // 如果不应该渲染此节点，直接返回null
      if (!shouldRenderNode()) {
        return null;
      }
      
      let iconElement;
      // 确定图标元素
      if (node.type === 'resources') {
        // 资源父节点使用资源图标
        iconElement = (
          <img 
            src={resourceIcon} 
            alt="资源图标" 
            style={{ 
              width: '16px', 
              height: '16px', 
              marginRight: '8px' 
            }}
          />
        );
      } else if (node.type === 'materials') {
        // 材料父节点使用产品图标
        iconElement = (
          <img 
            src={productIcon} 
            alt="材料图标" 
            style={{ 
              width: '16px', 
              height: '16px', 
              marginRight: '8px' 
            }}
          />
        );
      } else if (node.iconSrc) {
        iconElement = (
          <img 
            src={node.iconSrc} 
            alt={`${node.type} icon`} 
            style={{ 
              width: '16px', 
              height: '16px', 
              marginRight: '8px' 
            }}
          />
        );
      } else if (node.icon) {
        iconElement = node.icon;
      }
      
      let titleColor = '#333';
      let displayText = node.displayTitle || node.title;
      
      if (node.type === 'route') {
        titleColor = '#1766a3';
      } else if (node.type === 'operation') {
        titleColor = '#2a9d8f';
      } else if (node.type === 'step') {
        titleColor = '#e76f51';
      } else if (node.type === 'parameter') {
        // 显示参数名称
        displayText = node.title;
        if (node.value) {
          displayText += `: ${node.value}${node.unit ? node.unit : ''}`;
        }
      } else if (node.type === 'material') {
        // 显示材料名称
        displayText = node.title;
        if (node.quantity) {
          displayText += `: ${node.quantity}${node.unit ? node.unit : ''}`;
        }
      } else if (node.type === 'resource') {
        // 显示资源名称
        displayText = node.title;
        if (node.quantity) {
          displayText += `: ${node.quantity}个`;
        }
      }
      
      return (
        <div key={node.key} data-key={node.key}>
          <div 
            style={{ 
              display: 'flex', 
              alignItems: 'center',
              padding: '8px 0', 
              paddingLeft: `${level * 24}px`,
              paddingRight: '8px',
              cursor: 'pointer',
              backgroundColor: isSelected ? '#e6f7ff' : 'transparent',
              borderLeft: isSelected ? '3px solid #1766a3' : 'none',
              borderRadius: '4px',
              margin: '2px 0',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis'
            }}
          >
            {hasChildren && (
              <span 
                style={{ 
                  marginRight: '8px', 
                  fontSize: '12px', 
                  color: '#1766a3', 
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  width: '16px',
                  height: '16px',
                  flexShrink: 0
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  toggleNode(node.key);
                }}
              >
                {isExpanded ? <DownOutlined /> : <RightOutlined />}
              </span>
            )}
            {!hasChildren && <span style={{ width: '16px', display: 'inline-block', flexShrink: 0 }}></span>}
            {iconElement && (
              <span style={{ 
                marginRight: '8px', 
                color: titleColor,
                display: 'inline-flex',
                alignItems: 'center',
                flexShrink: 0
              }}>
                {iconElement}
              </span>
            )}
            <span 
              style={{ 
                color: titleColor,
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap'
              }}
              onClick={(e) => {
                e.stopPropagation();
                if (node.type === 'parameter') {
                  handleParameterClick(e, node);
                } else if (node.type === 'resource') {
                  handleResourceClick(e, node);
                } else if (node.type === 'material') {
                  handleMaterialClick(e, node);
                } else if (node.type === 'operation') {
                  handleOperationClick(e, node);
                } else if (node.type === 'step') {
                  handleStepClick(e, node);
                } else if (hasChildren) {
                  toggleNode(node.key);
                }
              }}
            >
              {displayText}
            </span>
          </div>
          {hasChildren && isExpanded && (
            <div>
              {renderTreeNodes(node.children, level + 1)}
            </div>
          )}
        </div>
      );
    }).filter(Boolean); // 过滤掉null节点
  };
  
  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString || dateString === '-') return '-';
    
    try {
      // 尝试解析日期字符串
      const date = new Date(dateString);
      
      // 验证日期是否有效
      if (isNaN(date.getTime())) {
        console.warn(`无效的日期格式: ${dateString}`);
        return dateString; // 返回原始字符串，不尝试格式化
      }
      
      // 使用date-fns库格式化日期
      return format(date, 'yyyy-MM-dd HH:mm:ss');
    } catch (error) {
      console.error('日期格式化错误:', error, dateString);
      // 发生错误时返回原始字符串
      return dateString || '-';
    }
  };

  // 渲染工艺详情内容
  const renderDetailContent = () => {
    if (!processDetail) {
      return (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin />
        </div>
      );
    }

    return (
      <div className="detail-content">
        <div className="detail-header">
          <div className="detail-title">基本信息</div>
          <Button 
            type="primary" 
            icon={<ProjectOutlined />}
            size="small"
            onClick={handleOpenFlowChart}
          >
            工艺流程图
          </Button>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">编码:</div>
          <div className="detail-value">{processDetail.code || '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">名称:</div>
          <div className="detail-value">{processDetail.name || '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">总工时:</div>
          <div className="detail-value">{processDetail.total_work_hour ? `${processDetail.total_work_hour} h` : '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">创建时间:</div>
          <div className="detail-value">{formatDate(processDetail.create_time)}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">更新时间:</div>
          <div className="detail-value">{formatDate(processDetail.update_time)}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">状态:</div>
          <div className="detail-value">{processDetail.status ? 
            (() => {
              switch(processDetail.status) {
                case 'active': return '已发布';
                case 'inactive': return '未发布';
                case 'draft': return '草稿';
                case 'archived': return '已归档';
                default: return processDetail.status;
              }
            })() : '-'}
          </div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">模板名称:</div>
          <div className="detail-value">{templateInfo ? templateInfo.name : '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">模板编码:</div>
          <div className="detail-value">{templateInfo ? templateInfo.code : '-'}</div>
        </div>
        
        {/* 使用ProcessFlowChart组件显示流程图 */}
        <ProcessFlowChart 
          routeId={routeId}
          isOpen={flowChartVisible} 
          onClose={handleCloseFlowChart} 
              />
      </div>
    );
  };

  // 渲染工序详情内容
  const renderOperationContent = () => {
    if (operationLoading) {
      return (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin />
        </div>
      );
    }
    
    if (!operationDetail) {
      return (
        <div className="table-container" style={{
          border: '1px solid #e8e8e8',
          position: 'relative',
          width: '100%',
          flex: 1,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: '#fff'
        }}>
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={
              <div style={{ textAlign: 'center' }}>
                <p style={{ fontSize: isMobile ? '14px' : '16px', color: '#999', marginBottom: '16px' }}>
                  请在{isMobile ? '上方' : '左侧'}选择一个工序查看详情
                </p>
                <div style={{ fontSize: '13px', color: '#666' }}>
                  <div style={{ marginBottom: '8px' }}>操作指引：</div>
                  <div style={{ marginBottom: '4px' }}>1. 在左侧工艺结构树中找到工艺路线节点</div>
                  <div style={{ marginBottom: '4px' }}>2. 展开工艺路线节点找到工序节点</div>
                  <div style={{ marginBottom: '4px' }}>3. 点击工序节点查看详细信息</div>
                </div>
              </div>
            }
          />
        </div>
      );
    }
    
    return (
      <div className="detail-content">
        <div className="detail-header">
          <div className="detail-title">工序信息</div>
          <div>
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              size="small"
            >
              编辑
            </Button>
          </div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">编码:</div>
          <div className="detail-value">{operationDetail.code || '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">名称:</div>
          <div className="detail-value">{operationDetail.name || '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">说明:</div>
          <div className="detail-value">{operationDetail.description || '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">创建时间:</div>
          <div className="detail-value">{formatDate(operationDetail.create_time)}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">更新时间:</div>
          <div className="detail-value">{formatDate(operationDetail.update_time)}</div>
        </div>
      </div>
    );
  };

  // 渲染工步详情内容
  const renderStepContent = () => {
    if (stepLoading) {
      return (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin />
        </div>
      );
    }
    
    if (!stepDetail) {
      return (
        <div className="table-container" style={{
          border: '1px solid #e8e8e8',
          position: 'relative',
          width: '100%',
          flex: 1,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: '#fff'
        }}>
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={
              <div style={{ textAlign: 'center' }}>
                <p style={{ fontSize: isMobile ? '14px' : '16px', color: '#999', marginBottom: '16px' }}>
                  请在{isMobile ? '上方' : '左侧'}选择一个工步查看详情
                </p>
                <div style={{ fontSize: '13px', color: '#666' }}>
                  <div style={{ marginBottom: '8px' }}>操作指引：</div>
                  <div style={{ marginBottom: '4px' }}>1. 在左侧工艺结构树中找到工序节点</div>
                  <div style={{ marginBottom: '4px' }}>2. 展开工序节点找到工步节点</div>
                  <div style={{ marginBottom: '4px' }}>3. 点击工步节点查看详细信息</div>
                </div>
              </div>
            }
          />
        </div>
      );
    }
    
    // 渲染参数详情
    const renderParameterDetail = () => {
      if (parameterLoading) {
        return <Spin size="small" />;
      }
      
      if (!parameterDetail) {
        return null;
      }
      
      // 安全地访问参数字段
      const safeParamDetail = {
        param_name: parameterDetail?.param_name || parameterDetail?.name || '-',
        param_value: parameterDetail?.param_value || parameterDetail?.value || '-',
        param_unit: parameterDetail?.param_unit || parameterDetail?.unit || '-',
        param_upper_limit: parameterDetail?.param_upper_limit || parameterDetail?.upper_limit || '-',
        param_lower_limit: parameterDetail?.param_lower_limit || parameterDetail?.lower_limit || '-',
        create_time: parameterDetail?.create_time || '-'
      };
      
      return (
        <div className="sub-detail-content" style={{ marginTop: '20px', padding: '16px', backgroundColor: '#f9f9f9', borderRadius: '4px' }}>
          <div className="detail-header">
            <div className="detail-title">参数详情</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">参数名称:</div>
            <div className="detail-value">{safeParamDetail.param_name}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">参数值:</div>
            <div className="detail-value">{safeParamDetail.param_value}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">单位:</div>
            <div className="detail-value">{safeParamDetail.param_unit}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">上限值:</div>
            <div className="detail-value">{safeParamDetail.param_upper_limit}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">下限值:</div>
            <div className="detail-value">{safeParamDetail.param_lower_limit}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">创建时间:</div>
            <div className="detail-value">{formatDate(safeParamDetail.create_time)}</div>
          </div>
        </div>
      );
    };
    
    // 渲染资源详情
    const renderResourceDetail = () => {
      if (resourceLoading) {
        return <Spin size="small" />;
      }
      
      if (!resourceDetail) {
        return null;
      }
      
      return (
        <div className="sub-detail-content" style={{ marginTop: '20px', padding: '16px', backgroundColor: '#f9f9f9', borderRadius: '4px' }}>
          <div className="detail-header">
            <div className="detail-title">资源详情</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">资源名称:</div>
            <div className="detail-value">{resourceDetail.resource_name || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">资源编码:</div>
            <div className="detail-value">{resourceDetail.resource_code || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">数量:</div>
            <div className="detail-value">{resourceDetail.quantity || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">单位:</div>
            <div className="detail-value">{resourceDetail.unit || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">使用时间:</div>
            <div className="detail-value">{resourceDetail.usage_time ? `${resourceDetail.usage_time} ${resourceDetail.time_unit || 'min'}` : '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">创建时间:</div>
            <div className="detail-value">{formatDate(resourceDetail.create_time)}</div>
          </div>
        </div>
      );
    };
    
    // 渲染材料详情
    const renderMaterialDetail = () => {
      if (materialLoading) {
        return <Spin size="small" />;
      }
      
      if (!materialDetail) {
        return null;
      }
      
      return (
        <div className="sub-detail-content" style={{ marginTop: '20px', padding: '16px', backgroundColor: '#f9f9f9', borderRadius: '4px' }}>
          <div className="detail-header">
            <div className="detail-title">材料详情</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">材料名称:</div>
            <div className="detail-value">{materialDetail.product_name || materialDetail.material_name || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">材料编码:</div>
            <div className="detail-value">{materialDetail.product_code || materialDetail.material_code || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">数量:</div>
            <div className="detail-value">{materialDetail.quantity || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">单位:</div>
            <div className="detail-value">{materialDetail.unit || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">创建时间:</div>
            <div className="detail-value">{formatDate(materialDetail.create_time)}</div>
          </div>
        </div>
      );
    };
    
    return (
      <div className="detail-content">
        <div className="detail-header">
          <div className="detail-title">工步信息</div>
          <div>
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              size="small"
            >
              编辑
            </Button>
          </div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">编码:</div>
          <div className="detail-value">{stepDetail.code || '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">名称:</div>
          <div className="detail-value">{stepDetail.name || '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">说明:</div>
          <div className="detail-value">{stepDetail.description || '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">工时:</div>
          <div className="detail-value">{stepDetail.work_hour ? `${stepDetail.work_hour} h` : '-'}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">创建时间:</div>
          <div className="detail-value">{formatDate(stepDetail.create_time)}</div>
        </div>
        
        <div className="detail-item">
          <div className="detail-label">更新时间:</div>
          <div className="detail-value">{formatDate(stepDetail.update_time)}</div>
        </div>
        
        {/* 根据detailType显示对应的详情 */}
        {detailType === 'parameter' && renderParameterDetail()}
        {detailType === 'resource' && renderResourceDetail()}
        {detailType === 'material' && renderMaterialDetail()}
      </div>
    );
  };

  // 自定义节点渲染组件
  const CustomNode = ({ data }) => {
    return (
      <div style={{
        padding: '10px',
        borderRadius: '5px',
        backgroundColor: '#f0f0f0',
        border: '1px solid #ddd',
        textAlign: 'center',
        width: '150px'
      }}>
        {data.label}
      </div>
    );
  };

  // 定义节点类型映射
  const nodeTypes = {
    custom: CustomNode,
  };

  // 处理打开流程图
  const handleOpenFlowChart = () => {
    // 设置流程图加载状态为true
    setFlowChartLoading(true);
    // 打开流程图对话框
        setFlowChartVisible(true);
    console.log('打开工艺流程图，routeId:', routeId);
  };
  
  // 处理关闭流程图
  const handleCloseFlowChart = () => {
    // 关闭流程图对话框
    setFlowChartVisible(false);
    // 延迟重置加载状态，确保动画顺畅
    setTimeout(() => {
      setFlowChartLoading(false);
    }, 300);
  };

  // 渲染参数详情内容
  const renderParameterDetailContent = () => {
    if (parameterLoading) {
      return (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin />
        </div>
      );
    }
    
    if (!parameterDetail) {
      return (
        <div className="table-container" style={{
          border: '1px solid #e8e8e8',
          position: 'relative',
          width: '100%',
          flex: 1,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: '#fff'
        }}>
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={
              <div style={{ textAlign: 'center' }}>
                <p style={{ fontSize: isMobile ? '14px' : '16px', color: '#999', marginBottom: '16px' }}>
                  请在{isMobile ? '上方' : '左侧'}选择一个参数查看详情
                </p>
                <div style={{ fontSize: '13px', color: '#666' }}>
                  <div style={{ marginBottom: '8px' }}>操作指引：</div>
                  <div style={{ marginBottom: '4px' }}>1. 在左侧工艺结构树中找到工步节点</div>
                  <div style={{ marginBottom: '4px' }}>2. 展开工步节点找到参数节点</div>
                  <div style={{ marginBottom: '4px' }}>3. 点击参数节点查看详细信息</div>
                </div>
              </div>
            }
          />
        </div>
      );
    }
    
    try {
      // 安全地访问参数字段
      const safeParamDetail = {
        param_name: parameterDetail?.param_name || parameterDetail?.name || '-',
        param_value: parameterDetail?.param_value || parameterDetail?.value || '-',
        param_unit: parameterDetail?.param_unit || parameterDetail?.unit || '-',
        param_upper_limit: parameterDetail?.param_upper_limit || parameterDetail?.upper_limit || '-',
        param_lower_limit: parameterDetail?.param_lower_limit || parameterDetail?.lower_limit || '-',
        create_time: parameterDetail?.create_time || '-'
      };
      
      return (
        <div className="detail-content">
          <div className="detail-header">
            <div className="detail-title">参数详情</div>
            <div>
              <Button 
                type="primary" 
                icon={<EditOutlined />}
                size="small"
              >
                编辑
              </Button>
            </div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">参数名称:</div>
            <div className="detail-value">{safeParamDetail.param_name}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">参数值:</div>
            <div className="detail-value">{safeParamDetail.param_value}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">单位:</div>
            <div className="detail-value">{safeParamDetail.param_unit}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">上限值:</div>
            <div className="detail-value">{safeParamDetail.param_upper_limit}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">下限值:</div>
            <div className="detail-value">{safeParamDetail.param_lower_limit}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">创建时间:</div>
            <div className="detail-value">{formatDate(safeParamDetail.create_time)}</div>
          </div>
        </div>
      );
    } catch (error) {
      console.error('渲染参数详情错误:', error);
      return (
        <div className="detail-content">
          <div className="detail-header">
            <div className="detail-title">参数详情</div>
          </div>
          <div style={{ padding: '20px', textAlign: 'center' }}>
            加载参数详情时出错，请稍后再试
          </div>
        </div>
      );
    }
  };

  // 渲染资源详情内容
  const renderResourceDetailContent = () => {
    if (resourceLoading) {
      return (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin />
        </div>
      );
    }
    
    if (!resourceDetail) {
      return (
        <div className="table-container" style={{
          border: '1px solid #e8e8e8',
          position: 'relative',
          width: '100%',
          flex: 1,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: '#fff'
        }}>
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={
              <div style={{ textAlign: 'center' }}>
                <p style={{ fontSize: isMobile ? '14px' : '16px', color: '#999', marginBottom: '16px' }}>
                  请在{isMobile ? '上方' : '左侧'}选择一个资源查看详情
                </p>
                <div style={{ fontSize: '13px', color: '#666' }}>
                  <div style={{ marginBottom: '8px' }}>操作指引：</div>
                  <div style={{ marginBottom: '4px' }}>1. 在左侧工艺结构树中找到工步节点</div>
                  <div style={{ marginBottom: '4px' }}>2. 展开工步节点找到资源节点</div>
                  <div style={{ marginBottom: '4px' }}>3. 点击资源节点查看详细信息</div>
                </div>
              </div>
            }
          />
        </div>
      );
    }
    
    try {
      // 定义资源参数表格列
      const parameterColumns = [
        {
          title: '参数名称',
          dataIndex: 'param_name',
          key: 'param_name',
          render: (text) => text || '-'
        },
        {
          title: '参数值',
          dataIndex: 'param_value',
          key: 'param_value',
          render: (text) => text || '-'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          key: 'unit',
          render: (text) => text || '-'
        }
      ];
      
      return (
        <div className="detail-content">
          <div className="detail-header">
            <div className="detail-title">资源详情</div>
            <div>
              <Button 
                type="primary" 
                icon={<EditOutlined />}
                size="small"
              >
                编辑
              </Button>
            </div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">资源名称:</div>
            <div className="detail-value">{resourceDetail.resource_name || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">资源编码:</div>
            <div className="detail-value">{resourceDetail.resource_code || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">资源类型:</div>
            <div className="detail-value">{resourceDetail.resource_type || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">资源型号:</div>
            <div className="detail-value">{resourceDetail.resource_model || resourceDetail.model || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">资源分类:</div>
            <div className="detail-value">{resourceDetail.resource_category || resourceDetail.category_name || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">资源状态:</div>
            <div className="detail-value">{resourceDetail.resource_status || resourceDetail.status || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">来源类型:</div>
            <div className="detail-value">{resourceDetail.resource_source || resourceDetail.source_type || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">使用数量:</div>
            <div className="detail-value">{resourceDetail.quantity || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">使用时间:</div>
            <div className="detail-value">{resourceDetail.usage_time ? `${resourceDetail.usage_time} ${resourceDetail.time_unit || 'min'}` : '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">描述:</div>
            <div className="detail-value">{resourceDetail.description || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">创建时间:</div>
            <div className="detail-value">{formatDate(resourceDetail.create_time)}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">更新时间:</div>
            <div className="detail-value">{formatDate(resourceDetail.update_time)}</div>
          </div>
          
          {/* 资源参数表格 */}
          {resourceDetail.resource_parameters && resourceDetail.resource_parameters.length > 0 && (
            <div className="sub-detail-content" style={{ marginTop: '16px' }}>
              <div className="detail-header">
                <div className="detail-title">资源参数</div>
              </div>
              <Table
                columns={parameterColumns}
                dataSource={resourceDetail.resource_parameters.map((item, index) => ({
                  ...item,
                  key: `param-${index}`
                }))}
                size="small"
                pagination={false}
                className="parameter-table"
                scroll={{ y: 200 }}
              />
            </div>
          )}
        </div>
      );
    } catch (error) {
      console.error('渲染资源详情错误:', error);
      return (
        <div className="detail-content">
          <div className="detail-header">
            <div className="detail-title">资源详情</div>
          </div>
          <div style={{ padding: '20px', textAlign: 'center' }}>
            加载资源详情时出错，请稍后再试
          </div>
        </div>
      );
    }
  };

  // 渲染材料详情内容
  const renderMaterialDetailContent = () => {
    if (materialLoading) {
      return (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin />
        </div>
      );
    }
    
    if (!materialDetail) {
      return (
        <div className="table-container" style={{
          border: '1px solid #e8e8e8',
          position: 'relative',
          width: '100%',
          flex: 1,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: '#fff'
        }}>
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={
              <div style={{ textAlign: 'center' }}>
                <p style={{ fontSize: isMobile ? '14px' : '16px', color: '#999', marginBottom: '16px' }}>
                  请在{isMobile ? '上方' : '左侧'}选择一个材料查看详情
                </p>
                <div style={{ fontSize: '13px', color: '#666' }}>
                  <div style={{ marginBottom: '8px' }}>操作指引：</div>
                  <div style={{ marginBottom: '4px' }}>1. 在左侧工艺结构树中找到工步节点</div>
                  <div style={{ marginBottom: '4px' }}>2. 展开工步节点找到材料节点</div>
                  <div style={{ marginBottom: '4px' }}>3. 点击材料节点查看详细信息</div>
                </div>
              </div>
            }
          />
        </div>
      );
    }
    
    try {
      return (
        <div className="detail-content">
          <div className="detail-header">
            <div className="detail-title">材料详情</div>
            <div>
              <Button 
                type="primary" 
                icon={<EditOutlined />}
                size="small"
              >
                编辑
              </Button>
            </div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">材料名称:</div>
            <div className="detail-value">{materialDetail.product_name || materialDetail.material_name || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">材料编码:</div>
            <div className="detail-value">{materialDetail.product_code || materialDetail.material_code || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">数量:</div>
            <div className="detail-value">{materialDetail.quantity || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">单位:</div>
            <div className="detail-value">{materialDetail.unit || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">材料类型:</div>
            <div className="detail-value">{materialDetail.material_type || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">规格型号:</div>
            <div className="detail-value">{materialDetail.material_spec || '-'}</div>
          </div>
          
          <div className="detail-item">
            <div className="detail-label">创建时间:</div>
            <div className="detail-value">{formatDate(materialDetail.create_time)}</div>
          </div>
        </div>
      );
    } catch (error) {
      console.error('渲染材料详情错误:', error);
      return (
        <div className="detail-content">
          <div className="detail-header">
            <div className="detail-title">材料详情</div>
          </div>
          <div style={{ padding: '20px', textAlign: 'center' }}>
            加载材料详情时出错，请稍后再试
          </div>
        </div>
      );
    }
  };

  return (
    <Layout className={`process-detail-container ${isMobile ? 'mobile-layout' : ''}`} style={{ overflow: 'hidden', height: '100%' }}>
      <style dangerouslySetInnerHTML={{ __html: customStyles + `
        .highlighted-row {
          background-color: #e6f7ff !important;
        }
        .highlighted-row td {
          background-color: #e6f7ff !important;
        }
        .parameter-table .ant-table-row:hover {
          cursor: pointer;
        }
        .table-container {
          height: calc(100% - 50px);
          overflow: hidden;
          display: flex;
          flex-direction: column;
        }
        .parameter-table {
          flex: 1;
        }
        .ant-pagination {
          margin: 16px 0;
          padding: 8px 0;
        }
        .ant-table-pagination.ant-pagination {
          margin: 16px 0;
          padding-bottom: 16px;
          text-align: center;
          width: 100%;
        }
        .ant-pagination-item, 
        .ant-pagination-prev, 
        .ant-pagination-next,
        .ant-pagination-jump-prev, 
        .ant-pagination-jump-next,
        .ant-select-selector {
          margin: 0 4px !important;
        }
        .ant-pagination-options {
          margin-left: 16px;
        }

        /* 修复页码不显示的问题 */
        .ant-pagination-item {
          display: inline-block !important;
          min-width: 32px !important;
          height: 32px !important;
          line-height: 30px !important;
          text-align: center !important;
          vertical-align: middle !important;
          list-style: none !important;
          background-color: #ffffff !important;
          border: 1px solid #d9d9d9 !important;
          border-radius: 2px !important;
          outline: 0 !important;
          cursor: pointer !important;
          user-select: none !important;
        }

        .ant-pagination-item-active {
          font-weight: 500 !important;
          background: #ffffff !important;
          border-color: #1766a3 !important;
        }

        .ant-pagination-item-active a {
          color: #1766a3 !important;
        }

        .ant-pagination-item a {
          display: block !important;
          padding: 0 6px !important;
          color: rgba(0, 0, 0, 0.85) !important;
          transition: none !important;
          text-decoration: none !important;
        }
      ` }} />
      <Content style={{ padding: '0', height: '100%', overflow: 'hidden' }}>
        <div className="content-wrapper" style={{ 
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden'
        }}>
          {/* 标题栏 */}
          <div style={{ 
            padding: isMobile ? '8px' : '16px',
            borderBottom: '1px solid #e8e8e8',
            background: '#fff',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
          }}>
            <div style={{ 
              fontWeight: 'bold', 
              fontSize: isMobile ? '14px' : '18px',
              display: 'flex',
              alignItems: 'center',
              color: '#1766a3'
            }}>
              <img 
                src={productProcessIcon} 
                alt="工艺详情" 
                style={{ 
                  width: '18px', 
                  height: '18px', 
                  marginRight: '8px' 
                }} 
              />
              <span>{code}工艺详情</span>
            </div>
          </div>
          
          {/* 内容区域 */}
          <div style={{ 
            flex: 1,
            overflow: 'hidden',
            height: 'calc(100% - 60px)',
            position: 'relative'
          }}>
            {/* 左侧树形结构 */}
            <div ref={treeContainerRef} className="tree-container" style={{ 
              width: isMobile ? '100%' : '40%',
              height: isMobile ? '50%' : '100%',
              padding: isMobile ? '8px' : '16px',
              background: '#fff',
              overflow: 'auto',
              borderRight: isMobile ? 'none' : '1px solid #e8e8e8',
              position: isMobile ? 'relative' : 'absolute',
              top: 0,
              left: 0,
              bottom: 0,
              boxShadow: isMobile ? '0 2px 4px rgba(0,0,0,0.1)' : 'none'
            }}>
              {/* 树形结构控制按钮 */}
              <div className="tree-control-buttons">
                <Tooltip title="展开至工序">
                  <Button 
                    type="text" 
                    icon={<NodeCollapseOutlined />} 
                    size="small" 
                    onClick={expandToOperations}
                  >
                    {!isMobile && "展开至工序"}
                  </Button>
                </Tooltip>
                <Tooltip title="展开至工步">
                  <Button 
                    type="text" 
                    icon={<NodeExpandOutlined />} 
                    size="small" 
                    onClick={expandToSteps}
                  >
                    {!isMobile && "展开至工步"}
                  </Button>
                </Tooltip>
                <Tooltip title="全部展开">
                  <Button 
                    type="text" 
                    icon={<ExpandOutlined />} 
                    size="small" 
                    onClick={expandAll}
                  >
                    {!isMobile && "全部展开"}
                  </Button>
                </Tooltip>
              </div>
              <Spin spinning={loading}>
                {treeData.length > 0 ? (
                  <div className="custom-tree">
                    {renderTreeNodes(treeData)}
                  </div>
                ) : (
                  <div style={{ padding: '16px', textAlign: 'center', color: '#999' }}>
                    暂无工艺数据
                  </div>
                )}
              </Spin>
            </div>
            
            {/* 右侧内容区域 */}
            <div className="right-content-area" style={{ 
              flex: 1,
              padding: isMobile ? '8px' : '16px',
              background: '#fff',
              overflow: 'hidden',
              position: 'absolute',
              top: isMobile ? '50%' : 0,
              right: 0,
              bottom: 0,
              width: isMobile ? '100%' : '60%',
              left: isMobile ? 0 : '40%'
            }}>
              {/* 自定义选项卡 */}
              <div className="custom-tabs">
                <div 
                  className={`custom-tab ${activeTab === 'details' ? 'active' : ''}`}
                  onClick={() => setActiveTab('details')}
                >
                  工艺详情
                </div>
                <div 
                  className={`custom-tab ${activeTab === 'operation' ? 'active' : ''}`}
                  onClick={() => setActiveTab('operation')}
                >
                  工序详情
                </div>
                <div 
                  className={`custom-tab ${activeTab === 'step' ? 'active' : ''}`}
                  onClick={() => setActiveTab('step')}
                >
                  工步详情
                </div>
                <div 
                  className={`custom-tab ${activeTab === 'parameter' ? 'active' : ''}`}
                  onClick={() => setActiveTab('parameter')}
                >
                  参数详情
                </div>
                <div 
                  className={`custom-tab ${activeTab === 'resource' ? 'active' : ''}`}
                  onClick={() => setActiveTab('resource')}
                >
                  资源详情
                </div>
                <div 
                  className={`custom-tab ${activeTab === 'material' ? 'active' : ''}`}
                  onClick={() => setActiveTab('material')}
                >
                  材料详情
                </div>
              </div>
              
              {/* 选项卡内容 */}
              <div style={{ overflow: 'auto', height: 'calc(100% - 48px)' }}>
                {activeTab === 'details' && renderDetailContent()}
                {activeTab === 'operation' && renderOperationContent()}
                {activeTab === 'step' && renderStepContent()}
                {activeTab === 'parameter' && renderParameterDetailContent()}
                {activeTab === 'resource' && renderResourceDetailContent()}
                {activeTab === 'material' && renderMaterialDetailContent()}
              </div>
            </div>
          </div>
        </div>
      </Content>
    </Layout>
  );
};

export default ProcessDetail; 